/*
 * Powered By 
 * Since 2010 - 2016
 */

package com.rf.business.control;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.rf.business.model.AutoRelease;
import com.rf.business.model.CardPhoto;
import com.rf.business.model.CardRelease;
import com.rf.business.model.Declaration;
import com.rf.business.model.TravelLog;
import com.rf.business.service.AutoReleaseService;
import com.rf.business.service.CardPhotoService;
import com.rf.business.service.CardReleaseService;
import com.rf.business.service.TravelLogService;
import com.rf.sys.annotation.SystemLog;
import com.rf.sys.frm.BaseController;
import com.rf.sys.model.DepUser;
import com.rf.sys.model.Department;
import com.rf.sys.model.User;
import com.rf.sys.service.CommonService;
import com.rf.sys.service.DepUserService;
import com.rf.sys.service.DepartmentService;
import com.rf.sys.service.UserService;
import com.rf.sys.utils.ConfigUtils;
import com.rf.sys.utils.DateUtils;
import com.rf.sys.utils.JsonUtils;
import com.rf.sys.utils.PageUtils;
import com.rf.sys.utils.UuidUtil;

@Controller
@RequestMapping("/bus/cardRelease")
public class CardReleaseController extends BaseController{
	/**
	 * 日志
	 */
	private static Logger log = LoggerFactory.getLogger(CardReleaseController.class);
	private static final long serialVersionUID = -120161117110147799L;
	
	@Resource
	private CardReleaseService cardReleaseService;
	@Resource
	private CommonService commonService;
	@Resource
	private DepartmentService departmentService;
	@Resource
	private CardPhotoService cardPhotoService;
	@Resource
	private TravelLogService travelLogService;

	@Resource
	private UserService userService;
	@Resource
	private DepUserService depUserService;
	@Resource
	private AutoReleaseService autoReleaseService;
	/**
	 * 初始化页面信息
	 * @param request,response
	 * @return ModelAndView
	 * @throws ServletException,IOException
	 */
	@RequestMapping(value = "index")
    public ModelAndView index (HttpServletRequest request, HttpServletResponse response) throws Exception{
		ModelAndView modelAndView = new ModelAndView();
		String url = "/business/cardRelease/nkkOutList";
		String type = request.getParameter("type");
		if("01".equals(type)){
			url = "/business/enterCard/zjt_list";
		}else if("02".equals(type)){
			url = "/business/enterCard/lxs_list";
		}else if("03".equals(type)){
			url = "/business/enterCard/bj_list";
		}else if("04".equals(type)){
			url = "/business/enterCard/gj_list";
		}else if("05".equals(type)){
			url = "/business/enterCard/port_list";
		}else if("08".equals(type)){
			url = "/business/cardRelease/ybdOutList";
		}else if("09".equals(type)){
			url = "/business/cardRelease/ygOutList";
		}else if("10".equals(type)){
			url = "/business/cardRelease/nkkOutList";
		}else if("11".equals(type)){
			url = "/business/cardRelease/gjOutList";
		}else if("12".equals(type)){
			url = "/business/cardRelease/hgOutList";
		}else if("13".equals(type)){
			url = "/business/cardRelease/bjOutList";
		}else if("14".equals(type)){
			url = "/business/cardRelease/zjtOutList";
		}
		modelAndView.setViewName(url);
		return modelAndView; 
    }
    
    /**
	 * 搜索页面信息
	 * @param Page,request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "query")
    @ResponseBody
    public void query (PageUtils pageUtils, CardRelease cardRelease, HttpServletRequest request, HttpServletResponse response ) throws Exception{
    	//获取分页、查询参数，进行数据封装
    	Map searchMap = cardReleaseService.getCardReleasePage(cardRelease, pageUtils);
    	super.responsePrint(request, response, JsonUtils.mapToJson(searchMap));
    }
    
    /**
     * 编辑页面初始化
     * @param request,response
	 * @return ModelAndView
	 * @throws ServletException,IOException
     */
    @RequestMapping(value = "edit")
    public ModelAndView edit (HttpServletRequest request, HttpServletResponse response ) throws Exception{
    	ModelAndView modelAndView = new ModelAndView();
		String id = request.getParameter("id");
		String carNo = request.getParameter("carNo");
		String addType = request.getParameter("addType");
		CardRelease cardRelease = new CardRelease();
		if(id != null && !id.equals("")){
			cardRelease = cardReleaseService.getCardReleaseByID(id);
			String entryTime = DateUtils.dateToString(cardRelease.getEntryTime(), ConfigUtils.DATEFORMATER1);
			modelAndView.addObject("cardRelease", cardRelease);
			modelAndView.addObject("entryTime", entryTime);
			if("10".equals(addType)){
				modelAndView.setViewName("/business/cardRelease/nkkEdit");//南卡口
			}else if("13".equals(addType)){
				modelAndView.setViewName("/business/cardRelease/bjEdit");//边检
			}else{
				modelAndView.setViewName("/business/cardRelease/edit");
			}
	        
		}else{
			if(carNo!=null && !carNo.equals("")){
				cardRelease.setCarNo(carNo);
			}
			cardRelease.setSerialNo(commonService.getSerialNo(2));//流水号
			cardRelease.setEntryExitType(ConfigUtils.CLCJ);
			modelAndView.addObject("cardRelease", cardRelease);
			modelAndView.addObject("addType",addType);
	        modelAndView.setViewName("/business/cardRelease/add");
		}
        return modelAndView; 
    }
    
    /**
     * 查看页面初始化
     * @param request,response
	 * @return ModelAndView
	 * @throws ServletException,IOException
     */
    @RequestMapping(value = "view")
    public ModelAndView view (HttpServletRequest request, HttpServletResponse response ) throws Exception{
    	ModelAndView modelAndView = new ModelAndView();
		String id = request.getParameter("id");
		CardRelease cardRelease = new CardRelease();
		if(id != null && !id.equals("")){
			cardRelease = cardReleaseService.getCardReleaseByID(id);	
			modelAndView.addObject("cardRelease", cardRelease);
	        modelAndView.setViewName("/business/cardRelease/view");
		}
        return modelAndView; 
    }
    
    /**
     * 保存数据信息
     * @param CardRelease,request,response
	 * @return ModelAndView
	 * @throws ServletException,IOException
     */
    @RequestMapping(value = "save")
    @SystemLog(module="放行卡管理",methods="放行卡-保存放行卡")
    public void save (HttpServletRequest request, HttpServletResponse response ) throws Exception{
    	JSONObject returnObj = new JSONObject();
    	Date d = new Date();
    	//获取当前登陆用户信息
    	Session session = SecurityUtils.getSubject().getSession();
		User user = (User)session.getAttribute("userSession");
    	String params = request.getParameter("data");
    	String showState = request.getParameter("showState");
    	String addType = request.getParameter("addType");
    	Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    	CardRelease cardRelease = gson.fromJson(params, CardRelease.class);
		if(cardRelease !=null && cardRelease.getId()!=null && !cardRelease.getId().equals("")){
			//修改
			cardRelease.setLastModifyTime(d);
			cardRelease.setLastModifyUser(user.getId());
			cardRelease.setIsProcess(ConfigUtils.YCLSTATE);
			cardReleaseService.updateCardRelease(cardRelease);
		}else{
			//新增
			String cardId = UuidUtil.get32UUID();
			cardRelease.setId(cardId);
			cardRelease.setCreateTime(d);
			cardRelease.setCreateUser(user.getId());
			cardRelease.setIsProcess(ConfigUtils.YCLSTATE);//已处理
			//南卡口新增时默认运营为已放行，南卡口为已放行
			if("10".equals(addType)){
				cardRelease.setOperationState(ConfigUtils.YFXSTATE);//运营--已放行
				cardRelease.setOpeCheckDate(d);
				cardRelease.setGateCheckState(ConfigUtils.YFXSTATE);//南卡口--已放行
				cardRelease.setGateCheckDate(d);
			}else{
				cardRelease.setOperationState(ConfigUtils.DFXSTATE);//运营--待放行
				cardRelease.setGateCheckState(ConfigUtils.DFXSTATE);//南卡口--待放行
			}
			List<AutoRelease> autoReleaseList = autoReleaseService.getAutoRelease();
			for(AutoRelease autoRelease:autoReleaseList){
				String extImp =  autoRelease.getEntryExitType();
				String auto = autoRelease.getIsAuto();
				if("bjcj".equals(extImp) && ConfigUtils.YESFX.equals(auto)){
					cardRelease.setBorderCheckDate(d);
					cardRelease.setBorderCheckState(ConfigUtils.YFXSTATE);//边检
				}else if("gjcj".equals(extImp) && ConfigUtils.YESFX.equals(auto)){
					cardRelease.setNationCheckDate(d);
					cardRelease.setNationCheckState(ConfigUtils.YFXSTATE);//国检
				}else{
					cardRelease.setBorderCheckState(ConfigUtils.DFXSTATE);
					cardRelease.setNationCheckState(ConfigUtils.DFXSTATE);
				}
			}
			cardRelease.setFinalCheckState(ConfigUtils.DFXSTATE);//终检亭
			cardRelease.setPortCheckState(ConfigUtils.DFXSTATE);//口岸
			cardRelease.setCustomCheckState(ConfigUtils.DFXSTATE);//海关
			cardReleaseService.addCardRelease(cardRelease);
			//处理图片
			if("2".equals(showState)){
	    		CardPhoto cardPhoto = new CardPhoto();
	    		cardPhoto.setCardId(cardId);
	    		String beforeCardId = "";
	    		List<Map<String, Object>> list = cardPhotoService.getCardPhotoByCarNo(cardRelease.getCarNo());
	    		for(int i=0;i<4;i++){
	    			Map<String, Object> map = list.get(i);
	    			String cid = (String)map.get("CARD_ID");
	    			if(i==0){
	    				beforeCardId = cid;
	    			}
	    			//判断是否同一组数据，防止照片数少于4张
	    			if(beforeCardId.equals(cid)){
	    				String type = (String)map.get("PHOTO_TYPE");
		    			if(ConfigUtils.ZMPTYPE.equals(type)){
		    				cardPhoto.setName("正面");
		    			}else if(ConfigUtils.CQPTYPE.equals(type)){
		    				cardPhoto.setName("侧前");
		    			}else if(ConfigUtils.CHPTYPE.equals(type)){
		    				cardPhoto.setName("侧后");
		    			}else if(ConfigUtils.HMPTYPE.equals(type)){
		    				cardPhoto.setName("后面");
		    			}
		    			cardPhoto.setPhotoPath((String)map.get("PHOTO_PATH"));
		    			cardPhoto.setId(UuidUtil.get32UUID());
		    			cardPhoto.setPhotoType(type);
		    			cardPhotoService.addCardPhoto(cardPhoto);
	    			}
	    		}
	    	}
		}
    	
		returnObj.element("message", "success");//成功
		super.responseJson(request, response, returnObj.toString());
    }
    
    /**
     * 删除数据信息
     * @param request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "delete")
    @ResponseBody
    @SystemLog(module="放行卡管理",methods="放行卡-删除放行卡")
    public void delete (HttpServletRequest request, HttpServletResponse response) throws Exception{
    	JSONObject returnObj = new JSONObject();
    	String ids = request.getParameter("ids");
    	cardReleaseService.deleteCardRelease(ids);
		returnObj.element("message", "success");//成功
		super.responseJson(request, response, returnObj.toString());
    }
    

    /**
     * 查验
     * @param cardRelease,request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "inspection")
    @ResponseBody
    @SystemLog(module="放行卡管理",methods="放行卡-查验")
    public void inspection (CardRelease cardRelease, HttpServletRequest request, HttpServletResponse response) throws Exception{
    	JSONObject returnObj = new JSONObject();
    	String type = request.getParameter("type");//获取页面type的值，判断是国检、海关、边检
    	if("1".equals(type)){
        	cardRelease.setNationCheckState(ConfigUtils.DFXSTATE);//国检改为待放行    		
    	}else if("2".equals(type)){
    		cardRelease.setCustomCheckState(ConfigUtils.DFXSTATE);//海关改为待放行  
    	}else if("3".equals(type)){
    		cardRelease.setBorderCheckState(ConfigUtils.DFXSTATE);//边检改为待放行  
    	}
    	cardReleaseService.updateCardRelease(cardRelease);
		returnObj.element("message", "success");//成功
		super.responseJson(request, response, returnObj.toString());
    }
    
    /**
     * 放行
     * @param cardRelease,request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "release")
    @ResponseBody
    @SystemLog(module="放行卡管理",methods="放行卡-放行")
    public void release (CardRelease cardRelease, HttpServletRequest request, HttpServletResponse response) throws Exception{
    	JSONObject returnObj = new JSONObject();
    	String type = request.getParameter("type");//获取页面type的值，判断是国检、海关、边检、终检亭
    	//获取当前登陆用户信息
    	Session session = SecurityUtils.getSubject().getSession();
		User user = (User)session.getAttribute("userSession");
    	Date d = new Date();
    	if("1".equals(type)){
    		cardRelease.setNationCheckDate(d);//国检操作时间
        	cardRelease.setNationCheckState(ConfigUtils.YFXSTATE);//放行    		
    	}else if("2".equals(type)){
    		cardRelease.setCustomCheckDate(d);//海关操作时间
        	cardRelease.setCustomCheckState(ConfigUtils.YFXSTATE);//放行    		
    	}else if("3".equals(type)){
    		cardRelease.setBorderCheckState(ConfigUtils.YFXSTATE);//放行 
        	cardRelease.setBorderCheckDate(d);// 边检操作时间
    	}else if("4".equals(type)){
    		cardRelease.setFinalCheckState(ConfigUtils.YFXSTATE);//放行 
    		cardRelease.setFinalCheckDate(d);// 终检亭操作时间	
    	}else if("5".equals(type)){
    		cardRelease.setGateCheckDate(d);//南卡口操作时间
        	cardRelease.setGateCheckState(ConfigUtils.YFXSTATE);//放行
    	}else if("6".equals(type)){
    		cardRelease.setOperationState(ConfigUtils.YFXSTATE);//运管
        	cardRelease.setOpeCheckDate(d);//放行
    	}
   
    	cardRelease.setLastModifyTime(d);//修改时间
    	cardRelease.setLastModifyUser(user.getId());//最后修改人
    	cardReleaseService.updateCardRelease(cardRelease);
		returnObj.element("message", "success");//成功
		super.responseJson(request, response, returnObj.toString());
    }
    
    /**
     * 退车
     * @param cardRelease,request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "returnCar")
    @ResponseBody
    @SystemLog(module="放行卡管理",methods="放行卡-退车")
    public void returnCar (CardRelease cardRelease, HttpServletRequest request, HttpServletResponse response) throws Exception{
    	JSONObject returnObj = new JSONObject();
    	String type = request.getParameter("type");//获取页面type的值
    	//获取当前登陆用户信息
    	Session session = SecurityUtils.getSubject().getSession();
		User user = (User)session.getAttribute("userSession");
		String depid = (String)session.getAttribute("depSessionId");
		Department department = departmentService.getDepartmentByID(depid);
    	Date d = new Date();
    	String id = cardRelease.getId();
    	CardRelease cardReleasee = cardReleaseService.getCardReleaseByID(id);
    	cardRelease.setBackCarUser(user.getId());//退车人
    	cardRelease.setBackCarTime(d);//退车时间
    	if(department != null){
    		cardRelease.setBackDepName(department.getName());
    	}
    	if("14".equals(type)){
    		cardRelease.setFinalCheckState(ConfigUtils.TCSTATE);//终检亭
    		cardRelease.setFinalCheckDate(d);
    		CardRelease newCardRelease = new CardRelease();
        	newCardRelease.setId(UuidUtil.get32UUID());
        	newCardRelease.setSerialNo(commonService.getSerialNo(1));
        	newCardRelease.setCarNo(cardReleasee.getCarNo());
        	newCardRelease.setChineseNum(cardReleasee.getChineseNum());
        	newCardRelease.setForeignNum(cardReleasee.getForeignNum());
        	newCardRelease.setTotalNum(cardReleasee.getTotalNum());
        	newCardRelease.setNationality(cardReleasee.getNationality());
        	newCardRelease.setEntryTime(d);
        	newCardRelease.setCarType(cardReleasee.getCarType());
        	//101101为入境车辆
        	newCardRelease.setEntryExitType("101101");
        	newCardRelease.setIsProcess("101301");
        	//边检亭
        	newCardRelease.setBorderCheckState("101402");
        	newCardRelease.setBorderCheckDate(d);
        	//国检
        	newCardRelease.setNationCheckDate(d);
        	newCardRelease.setNationCheckState("101402");
        	//海关
        	newCardRelease.setCustomCheckDate(d);
        	newCardRelease.setCustomCheckState("101402");
        	//男卡口
        	newCardRelease.setGateCheckDate(d);
        	newCardRelease.setGateCheckState("101402");
        	newCardRelease.setPortCheckDate(d);
        	newCardRelease.setPortCheckState("101402");
        	newCardRelease.setCreateTime(d);
        	newCardRelease.setCreateUser(user.getId());
        	cardReleaseService.addCardRelease(newCardRelease);
    	}else if("13".equals(type)){
    		cardRelease.setBorderCheckState(ConfigUtils.TCSTATE);//边检
    		cardRelease.setBorderCheckDate(d);
    		CardRelease newCardRelease = new CardRelease();
        	newCardRelease.setId(UuidUtil.get32UUID());
        	newCardRelease.setCarNo(cardReleasee.getCarNo());
        	newCardRelease.setChineseNum(cardReleasee.getChineseNum());
        	newCardRelease.setForeignNum(cardReleasee.getForeignNum());
        	newCardRelease.setTotalNum(cardReleasee.getTotalNum());
        	newCardRelease.setNationality(cardReleasee.getNationality());
        	newCardRelease.setEntryTime(d);
        	newCardRelease.setCarType(cardReleasee.getCarType());
        	//101101为入境车辆
        	newCardRelease.setEntryExitType("101101");
        	newCardRelease.setIsProcess("101301");
        	//边检亭
        	newCardRelease.setBorderCheckState("101402");
        	newCardRelease.setBorderCheckDate(d);
        	//国检
        	newCardRelease.setNationCheckDate(d);
        	newCardRelease.setNationCheckState("101402");
        	//海关
        	newCardRelease.setCustomCheckDate(d);
        	newCardRelease.setCustomCheckState("101402");
        	//男卡口
        	newCardRelease.setGateCheckDate(d);
        	newCardRelease.setGateCheckState("101402");
        	newCardRelease.setPortCheckDate(d);
        	newCardRelease.setPortCheckState("101402");
        	newCardRelease.setCreateTime(d);
        	newCardRelease.setCreateUser(user.getId());
        	cardReleaseService.addCardRelease(newCardRelease);
    	}else if("10".equals(type)){
        	cardRelease.setGateCheckDate(d);//南卡口操作时间
        	cardRelease.setGateCheckState(ConfigUtils.TCSTATE);//退车
    	}
    	cardRelease.setLastModifyTime(d);//最后修改时间
    	cardRelease.setLastModifyUser(user.getId());//最后修改人
    	cardReleaseService.updateCardRelease(cardRelease);
    	//生成入境放行卡
    	
		returnObj.element("message", "success");//成功
		super.responseJson(request, response, returnObj.toString());
    }
    
    /**
     * 加载车辆图片
     * @param cardRelease,request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "loadPic")
    @ResponseBody
    public void loadPic (HttpServletRequest request, HttpServletResponse response) throws Exception{
    	JSONObject returnObj = new JSONObject();
    	String carNo = request.getParameter("carNo");
    	List<Map<String, Object>> list = cardPhotoService.getCardPhotoByCarNo(carNo);
    	if(list.size()>0){
    		returnObj.element("message", "success");//成功
    		for(int i=0;i<4;i++){
    			Map<String, Object> map = list.get(i);
    			String type = (String)map.get("PHOTO_TYPE");
    			if(ConfigUtils.ZMPTYPE.equals(type)){
    				returnObj.element("zm", map.get("PHOTO_PATH"));//正面
    			}else if(ConfigUtils.CQPTYPE.equals(type)){
    				returnObj.element("cq", map.get("PHOTO_PATH"));//测前
    			}else if(ConfigUtils.CHPTYPE.equals(type)){
    				returnObj.element("ch", map.get("PHOTO_PATH"));//侧后
    			}else if(ConfigUtils.HMPTYPE.equals(type)){
    				returnObj.element("hm", map.get("PHOTO_PATH"));//后面
    			}
    		}
    	}else{
    		returnObj.element("message", "error");//未查询到
    	}
		super.responseJson(request, response, returnObj.toString());
    }
    /**
     * 1、撤销接车
     * 2、存入误接车日志
     * 3、判断是否超过三次，如果超过三次，锁账户
     * @param cardRelease
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "revokeAndSaveFault")
    @ResponseBody
    @SystemLog(module="业务功能",methods="旅行车误接车-撤销接车")
    public void revokeAndSaveFault(CardRelease cardRelease,HttpServletRequest request, HttpServletResponse response) throws Exception{
    	//撤销接车
    	CardRelease cardRelease1 = cardReleaseService.getCardReleaseByID(cardRelease.getId());
    	cardRelease1.setIsMeetCar(cardRelease.getIsMeetCar());
    	cardReleaseService.updateCardRelease(cardRelease1);
    	Session session = SecurityUtils.getSubject().getSession();
		User user = (User)session.getAttribute("userSession");
    	//保存误接车日志
		TravelLog travelLog = new TravelLog();
    	String id = UuidUtil.get32UUID();
    	travelLog.setCarNo(cardRelease1.getCarNo());
    	travelLog.setCreateTime(new Date());
    	travelLog.setCreateUser(user.getId());
    	travelLog.setId(id);
    	travelLog.setMeetCarUser(cardRelease1.getMeetCarUser());
    	travelLog.setSerialNo(cardRelease1.getSerialNo());
    	travelLog.setIsEffective("0");
    	DepUser dUser = new DepUser();
    	dUser.setUserId(cardRelease1.getMeetCarUser());
    	List<DepUser>  dUserList = depUserService.getDepUser(dUser);
    	if(dUserList != null && dUserList.size()>0){
    		DepUser dUser1 = dUserList.get(0);
    		travelLog.setTraId(dUser1.getDepId());
    	}
    	travelLogService.addTravelLog(travelLog);
    	TravelLog travelLog1 = new TravelLog();
    	travelLog1.setTraId(travelLog.getTraId());
    	travelLog1.setIsEffective("0");
    	//查询接车人误接车次数，是否等于三次，等于三次，锁定用户，并将这三条记录标识为无用
    	List<TravelLog> list = travelLogService.getTravelLog(travelLog1);
    	if(list != null && list.size() == 3){
    		Department department = departmentService.getDepartmentByID(travelLog1.getTraId());
    		department.setState("100102");
    		departmentService.updateDepartment(department);
    		
    		for(TravelLog traveLog : list){
    			traveLog.setIsEffective("1");
    			travelLogService.updateTravelLog(travelLog);
    		}
    	}
    	
    }
}


